//
//  ChooseView.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/8/11.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "ChooseView.h"

@interface ChooseView ()


@end

@implementation ChooseView

- (instancetype)initWithFrame:(CGRect)frame itemArray:(NSArray *)itemArray
{
    self = [super initWithFrame:frame];
    if (self) {
        _itemArray = itemArray;
        _selectIndex = 0;
        
        CGFloat width = frame.size.width / itemArray.count;
        for (int i = 0; i < itemArray.count; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(width * i, 0, width, frame.size.height);
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [button setImage:[[UIImage imageNamed:@"choose_normal"]modifyImageSize:CGSizeMake(10, 10)] forState:UIControlStateNormal];
            [button setImage:[[UIImage imageNamed:@"choose_select"]modifyImageSize:CGSizeMake(10, 10)] forState:UIControlStateSelected];
            [button setTitleColor:UIColorFromHex(0x999999) forState:UIControlStateNormal];
            [button setTitleColor:UIColorFromHex(0x333333) forState:UIControlStateSelected];
            button.tag = 10000 + i;
            [button setTitle:[NSString stringWithFormat:@" %@", itemArray[i]] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
            [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
            
            button.selected = (i == 0);
        }
    }
    return self;
}

- (void)action:(UIButton *)sender {
    NSInteger index = sender.tag - 10000;
    if (index == self.selectIndex) {
        return;
    }
    
    _selectIndex = index;
    
    for (int i = 0; i < self.itemArray.count; i++) {
        UIButton *button = [self viewWithTag:10000 + i];
        button.selected = (button == sender);
    }
    _selectIndex = sender.tag - 10000;
    if (self.vauleChange) {
        self.vauleChange(_selectIndex);
    }
}

@end
